function  verifyMobileTel (rule, value, callback){
    if(value && value!= '') {
        if (/^\d*$/.test(value)) {
            callback()
        } else {
            callback(new Error('手机号码只能由数字组成'))
        }
    } else {
        callback()
    }
}

// 验证数字，只允许1位小数
function verifyNumInput (form, key) {
    var str = form[key]
    var num = parseInt(str * 10) / 10
    if (!isNaN(num) && str[str.length - 1] !== '.') {
        form[key] = num
    }
}
// 校验身份证
function verifyIdCard(card) {
    var vcity={ 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
        21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",
        33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",
        42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",
        51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",
        63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"
    };
//检查号码是否符合规范，包括长度，类型
    var isCardNo = function(card)
    {
        //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
        var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
				// var reg = /(^\d{17}(\d|X|x)$)/;  //修改只校验18位身份证号
        if(reg.test(card) === false)
        {
            return false;
        }
        return true;
    };
//取身份证前两位,校验省份
    var checkProvince = function(card)
    {
        var province = card.substr(0,2);
        if(vcity[province] == undefined)
        {
            return false;
        }
        return true;
    };
//检查生日是否正确
    var checkBirthday = function(card)
    {
        var len = card.length;
        //身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字
        if(len == '15')
        {
            var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
            var arr_data = card.match(re_fifteen);
            var year = arr_data[2];
            var month = arr_data[3];
            var day = arr_data[4];
            var birthday = new Date('19'+year+'/'+month+'/'+day);
            return verifyBirthday('19'+year,month,day,birthday);
        }
        //身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X
        if(len == '18')
        {
            var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
            var arr_data = card.match(re_eighteen);
            var year = arr_data[2];
            var month = arr_data[3];
            var day = arr_data[4];
            var birthday = new Date(year+'/'+month+'/'+day);
            return verifyBirthday(year,month,day,birthday);
        }
        return false;
    };
//校验日期
    var verifyBirthday = function(year,month,day,birthday)
    {
        var now = new Date();
        var now_year = now.getFullYear();
        //年月日是否合理
        if(birthday.getFullYear() == year && (birthday.getMonth() + 1) == month && birthday.getDate() == day)
        {
            //判断companyName的范围（3岁到100岁之间)
            var time = now_year - year;
            if(time >= 3 && time <= 100)
            {
                return true;
            }
            return false;
        }
        return false;
    };
//校验位的检测
    var checkParity = function(card)
    {
        //15位转18位
        card = changeFivteenToEighteen(card);
        var len = card.length;
        if(len == '18')
        {
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var cardTemp = 0, i, valnum;
            for(i = 0; i < 17; i ++)
            {
                cardTemp += card.substr(i, 1) * arrInt[i];
            }
            valnum = arrCh[cardTemp % 11];
            if (valnum == card.substr(17, 1))
            {
                return true;
            }
            return false;
        }
        return false;
    };
//15位转18位身份证号
    var changeFivteenToEighteen = function(card)
    {
        if(card.length == '15')
        {
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var cardTemp = 0, i;
            card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
            for(i = 0; i < 17; i ++)
            {
                cardTemp += card.substr(i, 1) * arrInt[i];
            }
            card += arrCh[cardTemp % 11];
            return card;
        }
        return card;
    };

    //是否为空
    if(card === '')
    {
        // mui.alert('请输入身份证号，身份证号不能为空');
        return false;
    }
    //校验长度，类型
    if(isCardNo(card) === false)
    {
        //  mui.alert('您输入的身份证号码不正确，请重新输入');
        return false;
    }
    //检查省份
    if(checkProvince(card) === false)
    {
        //  mui.alert('您输入的身份证号码不正确,请重新输入');
        return false;
    }
    //校验生日
    if(checkBirthday(card) === false)
    {
        //  mui.alert('您输入的身份证号码生日不正确,请重新输入');
        return false;
    }
    //检验位的检测
    if(checkParity(card) === false)
    {
        //  mui.alert('您的身份证校验位不正确,请重新输入');
        return false;
    }
//    console.info("OK");
    return true;
};
function formatDate(date, fmt) {
    if(!(date instanceof Date)) return date;
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str));
        }
    }
    return fmt;

    function padLeftZero(str) {
        return ('00' + str).substr(str.length);
    }
}

/**
 * 字符串转日期类型，字符串格式仅支持：yyyy-MM-dd hh:mi:ss
 * @param {} str  yyyy-MM-dd
 * @returns date
 */
function convertDateTime(str) {
    let reg = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/;
    let regExp = new RegExp(reg);
    if (str && regExp.test(str)) {
        str = str.replace(" ", ":").replace(/\:/g, "-");
        let arr = str.split("-");
        let y = Number(arr[0]);
        let m = Number(arr[1]) - 1;
        let d = Number(arr[2]);
        let h = Number(arr[3]);
        let i = Number(arr[4]);
        let s = Number(arr[5]);
        let date = new Date(y, m, d, h, i, s);
        return date;
    }
    return null;
}
/**
 * @description 计算两个时间间隔分钟
 * @param {Date} d1 起始时间
 * @param {Date} d2 截止时间
 * @param {Boolean} roundDown 舍去小数点，默认：true
 */
function computeIntervalMin(d1, d2, roundDown = true) {
    if (d1 instanceof Date && d2 instanceof Date) {
        let interval = Math.abs(d2.getTime() - d1.getTime());
        if (roundDown) {
            return Math.floor(interval / (1000 * 60));
        } else {
            return Math.ceil(interval / (1000 * 60));
        }
    }
    return 0;
}

function createFormAndSubmit ({ formData, action = '', method = 'post', target = '_blank' }) {
    var dlform = document.createElement('form')
    dlform.style = 'display:none;'
    dlform.method = method
    dlform.action = action
    dlform.target = target

    for (var key in formData) {
        var data = formData[key]
        if (data instanceof Array) {
            // for (var i = 0, il = data.length; i < il; i++) {
                createInput(key + '[]', data)
            // }
        } else {
            if (data) {
                createInput(key, data)
            }
        }
    }
    document.body.appendChild(dlform)
    dlform.submit()
    document.body.removeChild(dlform)

    function createInput (key, data) {
        var hdnFilePath = document.createElement('input')
        hdnFilePath.type = 'hidden'
        hdnFilePath.name = key
        hdnFilePath.value = data
        dlform.appendChild(hdnFilePath)
    }
}

//base64转码（压缩完成后的图片为base64编码，这个方法可以将base64编码转回file文件）
function dataURLtoFile(dataurl,name) {
    var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr],name, { type: mime});
}
//压缩图片
function compressImg(file){
    var src;
    var files;
    var fileSize = parseFloat(parseInt(file['size'])/1024/1024).toFixed(2);
    var read = new FileReader();
    read.readAsDataURL(file);
    return new Promise(function(resolve, reject){
     read.onload = function (e) {
       var img = new Image();
       img.src = e.target.result;
       img.onload = function(){
         //默认按比例压缩
         var w = this.width,
           h = this.height;
         //生成canvas
         var canvas = document.createElement('canvas');
         var ctx = canvas.getContext('2d');
         var base64;
         // 创建属性节点
         canvas.setAttribute("width", w);
         canvas.setAttribute("height", h);
         ctx.drawImage(this, 0, 0, w, h);
         if(fileSize<1){
           //如果图片小于一兆 那么不执行压缩操作
           base64 = canvas.toDataURL(file['type'], 1);
         }else if(fileSize>1&&fileSize<2){
           //如果图片大于1M并且小于2M 那么压缩0.5
           base64 = canvas.toDataURL(file['type'], 0.5);
         }else{
           //如果图片超过2m 那么压缩0.2
           base64 = canvas.toDataURL(file['type'], 0.2);
         }
         // 回调函数返回file的值（将base64编码转成file）
         files = dataURLtoFile(base64,file['name']); //如果后台接收类型为base64的话这一步可以省略
         resolve(files)
       };
     };
    })
};

/* 读取文件 */
const readFile=(file)=>{
  return new Promise(resolve => {
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = ev => {
      resolve(ev.target.result)
    }
  })
}
   

export {
    createFormAndSubmit,
    formatDate,
    convertDateTime,
    computeIntervalMin,
    verifyIdCard,
    verifyMobileTel,
    verifyNumInput,
    compressImg,
    readFile
}
